/**
 * description
 * <p>fill description</p>
 * @author zido
 * @since 2017/6/3 0003
 */
import React from 'react'
import {
  Table,
  Icon,
  Input,
  DatePicker,
  Button,
  Modal,
  message
} from 'antd'
const {
  RangePicker
} = DatePicker
import BusinessAdd from '../../../../components/BusinessAdd'
import PropTypes from 'prop-types'
import {
  isEmpty
} from '../../../../Util'
import moment from 'moment'
import './Home.less'
import {
  Link
} from 'react-router'
const {
  Column
} = Table
const statesLabels = ['待审核', '已审核', '未通过']
const {
  confirm
} = Modal
export default class Home extends React.Component {

  handleTableChange(pagination, filters = {}, sorter = {}) {
    const {
      saveTableOptions
    } = this.props
    const {
      tableOptions
    } = this.props.home
    filters = {
      ...filters,
      key: tableOptions.filters.key,
      startTime: tableOptions.filters.startTime,
      endTime: tableOptions.filters.endTime,
    }
    saveTableOptions({
      pagination,
      filters,
      sorter,
    })
  }

  handleAddBusiness() {
    const {
      openAddModal
    } = this.props
    openAddModal()
  }
  handleAddBusinessCancel() {
    const {
      openAddModal
    } = this.props
    openAddModal(false)
  }
  componentDidMount() {
    const {
      loadData
    } = this.props
    loadData()
  }
  handleSubmitAddBusiness() {
    return () => {
      const {
        form
      } = this.props.home
      const {
        postAddData
      } = this.props
      form.validateFields((err, values) => {
        if (err) {
          message.error('有尚未处理的错误，请检查提交信息')
          return
        }
        const {
          userId,
          businessUserId,
          shopKeys,
          banKeys
        } = this.props.home
        values.shops.map((value, index) => {
          value.id = shopKeys[index].id
        })
        values.bankCards.map((value, index) => {
          value.id = banKeys[index].id
        })
        if (!isEmpty(values.user))
          values.user.id = userId
        if (!isEmpty(values.businessUser))
          values.businessUser.id = businessUserId
        postAddData(values).then(() => {
          this.refreshTable()
        })
      })
    }
  }
  saveFormRef(form, userId, businessUserId, shopKeys, banKeys) {
    const {
      saveUserInfo
    } = this.props
    saveUserInfo(form, userId, businessUserId, shopKeys, banKeys)
  }
  clearSearch() {
    const {
      saveTableOptions
    } = this.props
    const {
      tableOptions
    } = this.props.home
    const {
      pagination,
      filters,
      sorter
    } = tableOptions
    saveTableOptions({
      pagination,
      filters: {
        ...filters,
        key: null,
      },
      sorter,
    })
  }
  handleKeyChange(e) {
    const {
      saveTableOptions
    } = this.props
    const {
      tableOptions
    } = this.props.home
    const {
      pagination,
      filters,
      sorter
    } = tableOptions
    saveTableOptions({
      pagination,
      filters: {
        ...filters,
        key: e.target.value,
      },
      sorter,
    })
  }
  handleEdit(id) {
    const {
      openAddModal
    } = this.props
    openAddModal(true, id)
  }
  handleDelete(id) {
    const _this = this
    const {
      deleteByBusinessUserId
    } = this.props
    confirm({
      content: '是否确认删除？',
      onOk() {
        deleteByBusinessUserId(id).then(() => {
          _this.refreshTable()
        })
      }
    })

  }
  handleRangeChange(date) {
    const {
      saveTableOptions
    } = this.props
    const {
      tableOptions
    } = this.props.home
    const {
      pagination,
      filters,
      sorter
    } = tableOptions
    const options = {
      pagination,
      filters: {
        ...filters,
        startTime: isEmpty(date[0]) ? null : date[0].toDate().getTime(),
        endTime: isEmpty(date[1]) ? null : date[1].toDate().getTime(),
      },
      sorter,
    }
    saveTableOptions(options)
  }
  handlePass(id, p) {
    const _this = this
    confirm({
      content: '确认' + (p ? '通过' : '驳回') + '吗？',
      iconType: p ? 'like' : 'dislike',
      onOk() {
        const {
          pass
        } = _this.props
        pass(id, p).then(() => _this.refreshTable())
      },
      okText: '确认' + (p ? '通过' : '驳回'),
    })

  }

  refreshTable() {
    const {
      saveTableOptions
    } = this.props
    const {
      tableOptions
    } = this.props.home
    saveTableOptions(tableOptions)
  }

  render() {
    const {
      openAdd,
      modalLoading,
      editData,
      data,
      loading,
      tableOptions,
      seeLoading,
      loadingId,
      deleteLoading,
      deleteLoadingId
    } = this.props.home
    const {
      filters
    } = tableOptions
    const {
      startTime,
      endTime
    } = filters
    let searchText = filters.key
    return (
      <div>
        <div className='tool-box'>
          <Button type='primary' className='pull-right' size="large"><Link to='/business/add'><Icon type='plus'/>录入商家</Link></Button>
        </div>
        <Table dataSource={data.records} onChange={this.handleTableChange.bind(this)} rowKey={(record=>record.user.id)} loading={loading} pagination={ {
          data,
          ...{showQuickJumper:true,showSizeChanger:true,pageSizeOptions:['10','20','50'],showTotal:((total, range) => `从 ${range[0]} 到 ${range[1]} /共 ${total} 条数据`)}
        }}>
          <Column title='序列号' dataIndex="sort" render={(text,record)=>record.businessUser.sort} sorter={true} width="100px"/>
          <Column title='商家名称' dataIndex="key" render={(text,record)=>record.businessUser.nickname}  width="150px"
                  filterIcon={<Icon type="search" style={{ color: !isEmpty(searchText) ? '#108ee9' : '#aaa' }} />}
                  filterDropdown={
                    <div className="custom-filter-dropdown">
                      <Input
                        placeholder="请输入商家名称"
                        ref="search"
                        value={searchText}
                        onChange={this.handleKeyChange.bind(this)}
                        onPressEnter={this.handleKeyChange.bind(this)}
                      />
                      <Button type="primary" size="small" onClick={this.clearSearch.bind(this)}>清空</Button>
                    </div>
          }/>
          <Column title='常用联系人姓名' render={(text,record)=>record.businessUser.contactName}  width="150px"/>
          <Column title='常用联系手机号' render={(text,record)=>record.businessUser.phoneNumber}  width="150px"/>
          <Column title='常用联系微信' render={(text,record)=>record.businessUser.wechat}  width="120px"/>
          <Column title='常用联系qq' render={(text,record)=>record.businessUser.qq}  width="120px"/>
          <Column title='入驻时间'
                  dataIndex="create_time"
                  sorter={true}
                  render={(text,record)=>record.businessUser.createTimeLabel}
                  filterIcon = {<Icon type="schedule"  style={{ color: !isEmpty(startTime) && !isEmpty(endTime) ? '#108ee9' : '#aaa' }} />}
                  filterDropdown = {
                      <div ref="rangeContainer">
                        <RangePicker onChange={this.handleRangeChange.bind(this)} value={[moment(startTime || new Date()),moment(endTime || new Date())]} getCalendarContainer={()=>{
                          return this.refs.rangeContainer
                        }}/>
                      </div>
                  }  width="120px"
          />
          <Column title='审核状态' dataIndex="state" sorter={true} render={(text,record)=>statesLabels[record.businessUser.state]} filters={[
            {text:'待审核',value:'0',},
            {text:'已审核',value:'1',},
            {text:'未通过',value:'2',},
          ]}  width="100px"/>

          <Column title='操作' render={(record) => (
            <span className="btn-container">
              <Button type="primary" onClick={this.handleEdit.bind(this,record.businessUser.id)} loading={seeLoading && record.businessUser.id === loadingId}>查看</Button>
              {record.businessUser.state !== 1?(
                <span>
                  <Button type="primary" onClick={this.handlePass.bind(this,record.user.id,true)}><Icon type="like" />通过</Button>
                  {record.businessUser.state !== 2?<Button type="danger" onClick={this.handlePass.bind(this,record.user.id,false)}><Icon type="dislike" />驳回</Button>:null}
                </span>
              ):null}
              <Button type="danger" onClick={this.handleDelete.bind(this,record.businessUser.id)} loading={deleteLoading && record.businessUser.id === deleteLoadingId}>删除</Button>
            </span>
          )}  width={250}/>
        </Table>
        <BusinessAdd
          key={isEmpty(editData)?'businessAdd':editData.user.id}
          confirmLoading={modalLoading}
          insertForm={this.saveFormRef.bind(this)}
          onCancel={this.handleAddBusinessCancel.bind(this)}
          visible={openAdd}
          onOk={this.handleSubmitAddBusiness(this)}
          data={editData}/>
      </div>
    )
  }
}

Home.propTypes = {
  openAddModal: PropTypes.func.isRequired,
  postAddData: PropTypes.func.isRequired,
  loadData: PropTypes.func.isRequired,
  saveTableOptions: PropTypes.func.isRequired,
  saveUserInfo: PropTypes.func.isRequired,
  pass: PropTypes.func.isRequired,
  deleteByBusinessUserId: PropTypes.func.isRequired,
  home: PropTypes.object,
}